<template>
  <div>
    <BreadCrumbConfig :titleArr="titleArr" @back="cancel"></BreadCrumbConfig>
    <div class="baiduBinding">
      <div class="form-box">
        <el-form ref="infoform" class="form" :model="formData" :label-position="'left'"  label-width="180px" :rules="rules">
          <el-form-item :label="$t('config.channel.baiduBind001')" prop="name">
            <el-input v-model.trim="formData.name" size="mini"></el-input>
          </el-form-item>
          <el-form-item :label="$t('config.channel.baiduBind002')" prop="imidUrl">
            <el-input v-model.trim="formData.imidUrl" size="mini" :disabled="(formData._id || dataTodo === 'default') ? true : false" :placeholder="(formData.type || dataTodo === 'default') ? $t('config.channel.baiduBind003') : ''"></el-input>
          </el-form-item>
          <el-form-item :label="$t('config.channel.msgToPeer')" prop="to_peer">
            <el-select size="mini" v-model.trim="formData.to_peer" :placeholder="$t('public.pleasePick')">
              <el-option
                v-for="(item, index) in peerOptions"
                :key="index"
                :label="item.DisplayName"
                :value="item.Exten"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('config.channel.isUseRobt')" prop="robot">
            <el-select size="mini" v-model.trim="formData.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in robotOptions"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
            <el-select size="small" v-model.trim="formData.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
              <el-option value="">{{$t('public.pleasePick')}}</el-option>
              <el-option
                v-for="item in aiRobots"
                :key="item._id"
                :label="item.robot_name_new"
                :disabled="item.disabled"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.turnTip3')" prop="openTriggerWord">
            <el-radio-group v-model.trim="formData.openTriggerWord">
              <el-radio :label="true">{{$t('public.yes')}}</el-radio>
              <el-radio :label="false">{{$t('public.no')}}</el-radio>
            </el-radio-group>
            <question-tooltip
                    class="wechatTootip"
                    :direction="'bottom'"
                    :tipContent="$t('configLazyLoad.channel.turnTip4')">
            </question-tooltip>
          </el-form-item>
          <el-form-item :label="$t('configLazyLoad.channel.turnManWord')" prop="convert_words">
            <el-input size="mini" v-model.trim="formData.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
            <question-tooltip
                    class="wechatTootip"
                    :direction="'bottom'"
                    :tipContent="$t('configLazyLoad.channel.turnTip6')">
            </question-tooltip>
          </el-form-item>
          <el-form-item :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime">
            <el-radio-group v-model="formData.welcomePushTime" @change="pushTimeChange">
              <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
              <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
            <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
            <question-tooltip
              class="wechatTootip"
              :direction="'bottom'"
              :tipContent="$t('configLazyLoad.channel.wexinTip102')">
            </question-tooltip>
            <div class="placeholder_box">
              <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
                {{place.content}}
                <i class="iconfont icon-zhankai"></i>
              </dl>
            </div>
            <el-input size="mini" type="textarea" v-model="formData.welcome_msg"></el-input>
          </el-form-item>
        </el-form>
        <div class="footer">
          <el-button class="primary_btn" @click.stop="cancel()">{{$t('config.channel.prevStep')}}</el-button>
          <el-button type="primary" class="primary_btn" @click.stop="saveSet()">{{$t('public.save')}}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { deepClone } from '@/utils/m7Utils'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  export default{
    name: 'baiduBinding',
    components: {
      BreadCrumbConfig,
      questionTooltip
    },
    data () {
      return {
        titleArr: [this.$t('config.channel.baiduBCP'), this.$t('config.channel.baiduBind004')],
        peerOptions: [],  //  技能组列表
        robotOptions: [], //  机器人列表
        aiRobots: [],     //  机器人辅助座席列表
        placeholderArr: [ //  欢迎语占位符
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ],
        rules: {
          // imidUrl: [
          //   { required: true, message: '必填', trigger: 'blur' }
          // ],
          name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        },
        formData: {
          convert_words: "",
          imidUrl: "",
          name: "",
          openTriggerWord: true,
          robot: "",
          robotAssistId: "",
          to_peer: "",
          welcomePushTime: "access",
          welcome_msg: ""
        }
      }
    },
    props: {
      dataTodo: {
        type: String,
        default: 'add'
      },
      dataObj: {
        type: Object,
        default: {}
      }
    },
    methods: {
      cancel () {
        this.$emit('cancel')
      },
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.robotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.robotOptions = allRobot
            }
          })
        }
      },
//  更改欢迎语推送时机，改变欢迎语占位符展示
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }
          ]
          let str = ''
          if (this.formData.welcome_msg) {
            str = deepClone(this.formData.welcome_msg)
          }
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.formData.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      },
      //      点击添加欢迎语
      addPlaceholder (msg) {
        this.formData.welcome_msg += '{' + msg + '}'
      },
//      保存
      saveSet () {
        if (this.peerOptions.length === 0) {
          // this.$message.error('您还没设置技能组，请先到【渠道技能组】添加技能组!')
          this.$message(this.$t('configLazyLoad.channel.addSkillGroupTips'))
          return
        }
        this.$refs.infoform.validate((valid) => {
          if (valid) {
            let data = this.formData
            if (!this.formData.type && !data.imidUrl && this.dataTodo !== 'default') {
              this.$message.error(this.$t('config.channel.baiduBind005'))
              return
            }
            if (!data.to_peer) {
                // this.$message.error('请选择技能组')
                this.$message.error(this.$t('webchat.placeSkillsGrouop'))
                return
            }
            if (data.robot === '') {
              data.robotType = ''
            } else {
              this.robotOptions.forEach((item) => {
                if (item._id === data.robot) {
                  if (item.Nick) {
                    data.robotType = item.robotType
                  } else {
                    data.robotType = item.robot_type_new
                  }
                }
              })
            }
//          机器人辅助座席，增加assistRobotType参数
            if (data.robotAssistId) {
              this.aiRobots.map((item) => {
                if (data.robotAssistId === item._id) {
                  if (data.robotAssistId !== '') {
                    this.$set(data, 'assistRobotType', item.robotType)
                  } else {
                    this.$set(data, 'assistRobotType', '')
                  }
                }
              })
            }
            data.robot = data.robot ? data.robot : ''
            var action = 'saveBaiduOcpcConfig'
            if (data._id) {
              action = 'updateBaiduOcpcConfig'
            }
            if (this.dataTodo === 'default') {
              action = 'saveOcpcTemplateConfig'
            }
            this.$store.dispatch(action, data).then((req) => {
              if (req.success) {
                // this.$message.success('保存成功')
                this.$message.success(this.$t('config.channel.saveSuccess'))
                this.$emit('cancel')
              }
            })
          }
        })
      }
    },
    mounted () {
//      初始化数据
      if (this.dataObj._id) {
        this.formData = deepClone(this.dataObj)
        this.titleArr = [this.$t('config.channel.baiduBCP'), this.$t('config.channel.baiduBind006')]
      }
//      设置欢迎语菜单选项
      if (!this.formData.welcomePushTime) {
        this.$set(this.formData, 'welcomePushTime', 'access')
      }
      this.pushTimeChange(this.formData.welcomePushTime)
//      数据初始化openTriggerWord（是否开启触发词命中转人工）值默认为true
      if (this.formData.openTriggerWord === undefined) {
        this.$set(this.formData, 'openTriggerWord', true)
      }
//      获取技能组
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = this.$getCache('mailQueues')
        if (!mailQueues || mailQueues.length === 0) {
          return
        }
        this.peerOptions = mailQueues || []
      })
//      获取机器人列表
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig')
        this.robotOptions = robotConfig || []
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            this.robotOptions.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.robotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
    },
    beforeMount () {
      
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .baiduBinding
    height calc(100vh - 172px)
    overflow-y auto
  .form-box
    width 500px
    margin 0 auto
    .el-form-item .el-form-item__content
      text-align left
    .el-select
      width 100%
    .wechatTootip
      position absolute
      right -25px
    .form
      margin 20px 0
  .footer
    text-align center
    padding-bottom 20px
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
</style>